<?php 
namespace Home\Model;
use Think\Model;
/*
	会员类
*/
class UserModel extends Model {

	/**
	 * 会员登录
	 * @param string $mobile 手机(账号)
	 * @param string $password 加密密码
	 * @param bool $write_cookie 是否写入cookie Defualt:true
	 * @return bool/array 登录是否成功/{state}
	 */
	public function memberLogin($mobile, $password, $write_cookie = true)
	{
		$result = $this->where(array('mobile'=>$mobile))->find();
		if (!empty($result))
		{
			if ($result['status'] == 1)
			{
				return array('status' => -1, 'msg' => '账户被冻结');
			} elseif ($result['status'] == -1) {
				// 被删除账户
				return array('status' => -1, 'msg' => '手机号码或密码错误');
			}

			// 检查会员有效期是否过期
			if ($result['level'] != 0 && $result['valid_time'] != 0 && $result['valid_time'] <= NOW_TIME) {
				$this->where(array('id' => $result['id']))->save(array('level' => 0, 'valid_time' => 0));
				$result['level'] = 0;
				$result['valid_time'] = 0;
			}

			if ($result['password'] == $password)
			{
				// 登录成功
				// 写入 SESSION
				session('home_uid',$result['id']);

				//更新微信会员的uid
				$wx_info_id = session('wx_info_id');
				M('UserWxInfo')->where(array('id'=>$wx_info_id))->save(array('uid'=>$result['id']));
				
				// 储存User数据
				$home_member_info = array(
					'id' => $result['id'],
					'mobile' => $result['mobile'],
					'username' => $result['username'],
					'level' => $result['level'],				// 会员等级
					'weixin' => $result['weixin'],				// 绑定微信号
					'valid_time' => $result['valid_time'],		// 会员有效期
					'super_agent' => $result['super_agent'],	// 总代理
					'revenue' => $result['revenue'],
					'thumb' => $result['thumb'],
					'cash' => $result['cash'],
					'balance' => $result['balance'],
					'spread_url' => $this->getMemberSpreadUrl($result['id']),
					'higher_info' => $this->getMemberHigherInfo($result['id']),
					'top_super_agent' => $this->getMemberInfoById(spread_all($result['id'])),
					'createtime'=>$result['createtime']
				);
					// dump($home_member_info);
				session('home_member_info',$home_member_info);
				$this->checkVipValid($result['id']);
				//登录，取消注销状态
				$this->where('id = %d',$result['id'])->save(array('is_lock'=>0,'lastlogintime'=>NOW_TIME,'lastloginip'=>get_client_ip()));
				
				if ($write_cookie)
				{
					//登录后清楚登录状态，和第一登录session
					// session('home_wx',null);
					// session('frist_login',null);
					// 写入 COOKIE
					// 加密
					$cookie_mobile  = wgw_encrypt($result['mobile'],'E'); 
					$cookie_passwd   = wgw_encrypt($result['password'],'E'); 
					//设置过期时间为一周
					cookie('home_mobile',$cookie_mobile,NOW_TIME + 7*86400);//NOW_TIME + 7*86400
					cookie('home_passwd',$cookie_passwd,NOW_TIME + 7*86400);//7*86400

				}

				return true;
			}
		}

		return array('status' => -1, 'msg' => '手机号码或密码错误');
	}













	/**
	 * 微信授权会员自动登录
	 * @param string $mobile 手机(账号)
	 * @param string $password 加密密码
	 * @param bool $write_cookie 是否写入cookie Defualt:true
	 * @return bool/array 登录是否成功/{state}
	 */
	public function memberAutoLogin($uid)
	{
		$result = $this->where(array('id'=>$uid))->find();
		
		if (!empty($result))
		{
			/*if ($result['status'] == 1)
			{
				return array('status' => -1, 'msg' => '账户被冻结');
			} elseif ($result['status'] == -1) {
				// 被删除账户
				return array('status' => -1, 'msg' => '手机号码或密码错误');
			}*/

			// 检查会员有效期是否过期
			if ($result['level'] != 0 && $result['valid_time'] != 0 && $result['valid_time'] <= NOW_TIME) {
				$this->where(array('id' => $result['id']))->save(array('level' => 0, 'valid_time' => 0));
				$result['level'] = 0;
				$result['valid_time'] = 0;
			}


			// 登录成功
			// 写入 SESSION
			session('home_uid',$result['id']);

			//更新微信会员的uid
			$wx_info_id = session('wx_info_id');
			M('UserWxInfo')->where(array('id'=>$wx_info_id))->save(array('uid'=>$result['id']));
			
			// 储存User数据
			$home_member_info = array(
				'id' => $result['id'],
				'mobile' => $result['mobile'],
				'username' => $result['username'],
				'level' => $result['level'],				// 会员等级
				'weixin' => $result['weixin'],				// 绑定微信号
				'valid_time' => $result['valid_time'],		// 会员有效期
				'super_agent' => $result['super_agent'],	// 总代理
				'revenue' => $result['revenue'],
				'thumb' => $result['thumb'],
				'cash' => $result['cash'],
				'balance' => $result['balance'],
				'spread_url' => $this->getMemberSpreadUrl($result['id']),
				'higher_info' => $this->getMemberHigherInfo($result['id']),
				'top_super_agent' => $this->getMemberInfoById(spread_all($result['id'])),
				'createtime'=>$result['createtime']
			);

			session('home_member_info',$home_member_info);
			
			//$this->checkVipValid($result['id']);
			//登录，取消注销状态
			$this->where('id = %d',$result['id'])->save(array('is_lock'=>0,'lastlogintime'=>NOW_TIME,'lastloginip'=>get_client_ip()));
				
			
		}

	}






	/**
	 * 尝试自动登录
	 * @return bool 登录是否成功
	 */
	public function tryAutoLogin()
	{
		$mobile = cookie('home_mobile');	// Cookie 中 手机号码
		$passwd = cookie('home_passwd');	// Cookie 中 密码
		// Cookie 是否存在
		if ($mobile &&  $passwd)
		{
			// 解密
			$d_mobile = wgw_encrypt($mobile,'D');
			$d_passwd = wgw_encrypt($passwd,'D');
			// 登录
			$judge = D('User')->memberLogin($d_mobile, $d_passwd);
			if ($judge !== true)
			{
					
				// 登录验证失败 移除 cookie 避免多次且无效的尝试
				cookie('home_mobile',null);
				cookie('home_passwd',null);

				return false;
			}
			else
			{
				return true;
			}
		}
		
		//如果是微信，寻找openid,
		if(is_weixin() && C('is_wx') && !session('home_wx')){
			if(session('first_login') == 'true'){
				return false;
			}else{
				webchecklogin(true);
			}
		}
		return false;
	}

	/**
	 * 获取会员推广链接
	 * @param int $uid 会员ID
	 * @return string URL地址
	 */
	public function getMemberSpreadUrl($uid)
	{
		return U('Home/Index/index',array('register_id' => $uid),true,true);
	}

	/**
	 * 根据ID查询会员信息
	 * @param int $uid 会员id
	 * @param string $field 需要返回的字段
	 * @return array 会员信息
	 */
	public function getMemberInfoById($uid,$field = 'id,mobile,level,username,weixin,valid_time'){
		// $result  = $this->alias('u')->join('LEFT JOIN __USER_RELATIONSHIP__ as ur on u.id = ur.user_id')->where('u.id = %d',$uid)->field('u.*')->find();
		$result  = $this->where(array('id' => $uid))->field($field)->find();
		return $result;
	}
	
	/**
	 * 查询会员上级信息
	 * @param int $uid 会员id
	 * @param int $type 类型
	 * @return array 上级信息
	 */
	public function getMemberHigherInfo($uid){
		$info = M('UserRelationship')->where("subordinate_user = {$uid}")->field('user_id')->find();
		if ($info)
		{
			// $result = $this->where("id = {$info['user_id']}")->find();
			$result = $this->getMemberInfoById($info['user_id'],'id,username,weixin');
		}
		else
		{
			$weixin = D('Options')->getOpts(array('option_name'=>'weixin1'));
			$weixin1 = !empty($weixin['weixin1'])?$weixin['weixin1']:'官方推广';
			$result = array(
				'username' => '官方推广',
				'weixin' => $weixin1
			);
		}
		return $result;
	}

	/**
	 * 获取会员下线会员
	 * @param int $uid 会员ID
	 * @param int $page 查询页数
	 * @param int $limit 查询条数
	 * @param int $sort 排序 1:正序 -1:反序
	 * @return array 会员ID组
	 */
	public function getDownMember($uid, $page = 1, $limit = 10, $sort = 0)
	{
		$order = ($sort == 1) ? 'id asc' : 'id desc';
		// $uid_list = M('UserRelationship')->where(array('user_id' => $uid))->order($order)->limit($limit)->page($page)->field('subordinate_user')->select();
		$uid_list = M('UserRelationship')->where(array('user_id' => $uid))->order($order)->page($page)->getField('subordinate_user',$limit);
			// dump($uid_list);
		if (is_array($uid_list))
		{
			$user_list = $this->where(array('id' => array('in', $uid_list),'status' => array('neq',-1)))->order($order)->getField('id,username,weixin,level,createtime');
			foreach ($user_list as $key => $value) {
				$user_list[$key]['strTime'] = date("Y年m月d日 H:i",$value['createtime']);
			}
		}

		return $user_list;
	}

	/**
	 * 注册（新建）用户
	 * @param array $data User 表新用户数据
	 * @param int $puid 介绍人UID Default:0
	 * @return bool 
	 */
	public function registerMember($data, $puid)
	{
		// 写入用户数据表
		$new_uid = $this->add($data);
		
		if (!$new_uid)
		{
			return false;
		}
		
		if ($puid) 
		{
			$p_data = array(
				'user_id' => $puid,
				'subordinate_user' => $new_uid,
				'createtime' => $data['createtime'],
			);
			$result = M('UserRelationship')->add($p_data);
			if (!$result)
			{
				return false;
			}
		}
		
		return $new_uid;
	}
	
	//pos记录表插上记录
	public function insert_pos_apply($data){
		$result = M('PosApply')->add($data);
		return $result;
	}
	
	//查询pos记录表是否有会员的数据
	public function select_pos_apply($uid,$status){
		$result = M('PosApply')->where('uid = %d',$uid)->find();
		return $result;
	}

	/**
	 * 检查重置手机验证码
	 * @param string $captcha 验证码
	 * @return bool 匹配结果
	 */
	public function checkResetCaptcha($captcha,$mobile)
	{
		// $check = cookie('reset_captcha');
		$check = M('SmsCode')->where("mobile = '{$mobile}' and type = '0'")->order("id desc")->find();

		if ($check['createtime'] + 600 - NOW_TIME > 0 && $check['code'] == $captcha)
		{
			M('SmsCode')->where(array('id'=>$check['id']))->save(array('type'=>1));
			return true;
		}
		return false;
	}

	/**
	 * 检查会员有效期，如过期则移除会员等级
	 * @param  int $uid 会员ID
	 * @return void     无返回值
	 */
	public function checkVipValid($uid)
	{
		// 会员信息
		$userInfo = $this->where(array('id'=>$uid))->field('id,valid_time,level')->find();
		if ($userInfo && $userInfo['level'] != 0) {
			if ($userInfo['valid_time'] != 0 && $userInfo['valid_time'] <= NOW_TIME) {
				// 会员过期，降会员等级更改为0
				$this->where(array('id' => $uid))->save(array('level' => 0));
				// 修改 SESSION
				session('home_member_info.level',0);
			}
		}
	}

	/**
	 * 总代理删除会员
	 * @param  int  $uid    删除会员ID
	 * @param  int  $do_uid 总代理ID 默认：当前用户
	 * @return bool         成功与否
	 */
	public function deleteUser($uid, $do_uid = 0)
	{
		if (!$do_uid && session('home_uid')) {
			$do_uid = session('home_uid');
		}
		// 检查 总代理权限
		$superAgent = $this->where(array('id' => $do_uid))->getField('super_agent');
		
		if ($superAgent) {
			// 标记删除状态
			$this->where(array('id' => $uid))->save(array('status' => -1));
			/* 被删除会员的下线 - 归被删除用户的上级总代 */
			// 获得删除会员上级总代
			$topAgent = intval(spread_all($uid));
			// 修改删除会员下线会员为上级总代直属下线
			M('UserRelationship')->where(array('user_id' => $uid))->save(array('user_id' => $topAgent));
			// 记录删除日志
			$data = array(
				'uid' => $uid,
				'do_uid' => $do_uid,
				'do_time' => NOW_TIME,
			);
			M('UserDelete')->add($data);
			return true;
		}
		else
		{
			return false;
		}
	}
}
